<?php

namespace addons\shopro\service\user;

use fast\Random;
use app\common\library\Auth;
use app\admin\model\shopro\user\User as UserModel;
use think\Db;
class UserAuth
{

    /**
     * 认证用户
     *
     * @var object|null
     */
    protected $auth = null;

    public function __construct()
    {
        $this->auth = Auth::instance();
    }

    /**
     * 用户注册
     *
     * @param array $params 注册信息
     * @param array $params 至少包含 mobile 和 email 中的一个
     * @return object|array
     */
    public function empowerregister($mobile,$recommend)
    {
        $verification = [];

        if(!empty($params['username'])) {
            $username =  $params['username'];
            $verification['username'] = 1;
        }else {
            $username = Random::alnum(8);
        }
        if(!empty($mobile)) {
            $verification['mobile'] = 1;
        }else {
            $mobile = '';
        }
        if(!empty($params['email'])) {
            $email =  $params['email'];
            $verification['email'] = 1;
        }else {
            $email = '';
        }
        $rec = UserModel::where(['mobile' => $recommend])->find();

        $recUid = $rec['id'] ?? 0;
        if(!empty($params['password'])) {
            $password =  $params['password'];
            $verification['password'] = 1;
        }else {
            $password = Random::alnum(8);
        }

        $userDefaultConfig = $this->getUserDefaultConfig();

        $extend = [
            'avatar' => !empty($params['avatar']) ? $params['avatar'] : $userDefaultConfig['avatar'],
            'nickname' => !empty($params['nickname']) ? $params['nickname'] : $userDefaultConfig['nickname'] . $username,
            'group_id' => $userDefaultConfig['group_id'] ?? 1
        ];

        $ret = $this->auth->register($username, $password, $email, $mobile, $extend, $recUid);
        if ($ret) {
            $user = $this->auth->getUser();

            $user->verification = $verification;
            $user->save();

            $hookData = ['user' => $user];
            \think\Hook::listen('user_register_after', $hookData);

            return $this->auth;
        } else {
            error_stop($this->auth->getError());
        }
    }
 /**
     * 授权登陆用户注册
     *
     * @param array $params 注册信息
     * @param array $params 至少包含 mobile 和 email 中的一个
     * @return object|array
     */
    public function user_contact($monbile,$userid)
    {
        $users = auth_user();
        if(empty($monbile))
        {
            error_stop('请输入安置人');
        }
        $rec = UserModel::where(['mobile' => $monbile])->find();
        if(empty($rec))
        {
            error_stop('安置人不存在');
        }
        $anzhiuser = UserModel::where(['id' => $userid])->find();
        if(!empty($anzhiuser['father_user_id'])){
            error_stop('当前会员已有安置人');
        }
        if($anzhiuser['id']==$rec['id']){
            error_stop('安置人不能安置自己');
        }
        $user = new UserModel();
        $params=['father_user_id'=>$rec['id']];
        $ret=$user->save($params,['id'=>$userid]);
        if ($ret) {
            $remark=$users['mobile']."将会员".$anzhiuser['mobile'].'安置到'.$rec['mobile'];
            $insert=array(
              'father_id'=>$rec['id'],//上级id
              'event'=>'',
              'remark'=>$remark,
              'oper_id'=>$rec['id'],//操作人
              'user_id'=>$userid,//被安置的人
              'createtime'=>time(),//
            );
            Db::name('shopro_user_father_log')->insert($insert);

        } else {
            error_stop($this->auth->getError());
        }
    }

    /**
     * 授权登陆用户注册
     *
     * @param array $params 注册信息
     * @param array $params 至少包含 mobile 和 email 中的一个
     * @return object|array
     */
    public function user_invite($monbile,$subordinatemobile,$id)
    {

        if(!empty($monbile))
        {
            $rec = UserModel::where(['mobile' => $monbile])->find();
            if(empty($rec))
            {
                error_stop('邀请人有误');
            }
            $user = auth_user();
            if(!empty($user['parent_user_id'])){
                error_stop('当前会员已有邀请人');
            }
            if($rec['id']==$user['id']){
                error_stop('邀请人不能是自己');
            }
            $usermodel = new UserModel();
            $params=['parent_user_id'=>$rec['id']];
            $ret=$usermodel->save($params,['id'=>$id]);
            if ($ret) {

            } else {
                error_stop($this->auth->getError());
            }

        }
    }

    /**
     * 授权登陆用户注册
     *
     * @param array $params 注册信息
     * @param array $params 至少包含 mobile 和 email 中的一个
     * @return object|array
     */
    public function subordinate_user_invite($monbile,$subordinatemobile,$id)
    {
        if(!empty($subordinatemobile)){
            $rec = UserModel::where(['mobile' => $subordinatemobile])->find();
            if(empty($rec))
            {
                error_stop('绑定下级手机号有误');
            }
            if(!empty($rec['parent_user_id'])){
                error_stop('当前会员已有邀请人');
            }
            $user = auth_user();
            $usermodel = new UserModel();
            $params2=['parent_user_id'=>$user['id']];
            $ret=$usermodel->save($params2,['id'=>$rec['id']]);
            if ($ret) {

            } else {
                error_stop($this->auth->getError());
            }
        }
    }
    /**
     * 授权登陆用户注册
     *
     * @param array $params 注册信息
     * @param array $params 至少包含 mobile 和 email 中的一个
     * @return object|array
     */
    public function register($params)
    {
        $verification = [];

        if(!empty($params['username'])) {
            $username =  $params['username'];
            $verification['username'] = 1;
        }else {
            $username = Random::alnum(8);
        }
        if(!empty($params['mobile'])) {
            $mobile =  $params['mobile'];
            $verification['mobile'] = 1;
        }else {
            $mobile = '';
        }
        if(!empty($params['realname'])) {
            $realname =  $params['realname'];
         //   $verification['realname'] = 1;
        }else {
            $realname = '';
        }
        if(!empty($params['idcard'])) {
            $idcard =  $params['idcard'];
           // $verification['idcard'] = 1;
        }else {
            $idcard = '';
        }
        if(!empty($params['email'])) {
            $email =  $params['email'];
            $verification['email'] = 1;
        }else {
            $email = '';
        }
        $recommend = $params['recommend'] ?? '';
        if(empty($recommend))
        {
            error_stop('请输入推荐人');
        }
        $rec = UserModel::where(['mobile' => $recommend])->find();
        if(empty($rec))
        {
            error_stop('推荐人有误');
        }
        $recUid = $rec['id'] ?? 0;
        if(!empty($params['password'])) {
            $password =  $params['password'];
            $verification['password'] = 1;
        }else {
            $password = Random::alnum(8);
        }

        if ($username || $mobile || $email) {
            $user = UserModel::where(function ($query) use ($mobile, $email, $username) {
                if ($mobile) {
                    $query->whereOr('mobile', $mobile);
                }
                if ($email) {
                    $query->whereOr('email', $email);
                }
                if ($username) {
                    $query->whereOr('username', $username);
                }
            })->find();

            if ($user) {
                error_stop('账号已注册，请直接登录');
            }
        }

        $userDefaultConfig = $this->getUserDefaultConfig();

        $extend = [
            'avatar' => !empty($params['avatar']) ? $params['avatar'] : $userDefaultConfig['avatar'],
            'nickname' => !empty($params['nickname']) ? $params['nickname'] : $userDefaultConfig['nickname'] . $username,
            'group_id' => $userDefaultConfig['group_id'] ?? 1
        ];

        $ret = $this->auth->register($username, $password, $email, $mobile, $extend, $recUid,$idcard,$realname);

        if ($ret) {
            $user = $this->auth->getUser();

            $user->verification = $verification;
            $user->save();

            $hookData = ['user' => $user];
            \think\Hook::listen('user_register_after', $hookData);

            return $this->auth;
        } else {
            error_stop($this->auth->getError());
        }
    }


    /**
     * 用户注册
     *
     * @param array $params 注册信息
     * @param array $params 至少包含 mobile 和 email 中的一个
     * @return object|array
     */
    public function addUser($params)
    {
        $verification = [];

        if(!empty($params['username'])) {
            $username =  $params['username'];
            $verification['username'] = 1;
        }else {
            $username = Random::alnum(8);
        }
        if(!empty($params['mobile'])) {
            $mobile =  $params['mobile'];
            $verification['mobile'] = 1;
        }else {
            $mobile = '';
        }
        if(!empty($params['email'])) {
            $email =  $params['email'];
            $verification['email'] = 1;
        }else {
            $email = '';
        }
        $recommend = $params['recommend'] ?? '';
        if(empty($recommend))
        {
            error_stop('请输入推荐人');
        }
        $rec = UserModel::where(['mobile' => $recommend])->find();
        if(empty($rec))
        {
            error_stop('推荐人有误');
        }
        $recUid = $rec['id'] ?? 0;
        if(!empty($params['password'])) {
            $password =  $params['password'];
            $verification['password'] = 1;
        }else {
            $password = Random::alnum(8);
        }

        if ($username || $mobile || $email) {
            $user = UserModel::where(function ($query) use ($mobile, $email, $username) {
                if ($mobile) {
                    $query->whereOr('mobile', $mobile);
                }
                if ($email) {
                    $query->whereOr('email', $email);
                }
                if ($username) {
                    $query->whereOr('username', $username);
                }
            })->find();

            if ($user) {
                error_stop('账号已注册');
            }
        }

        $userDefaultConfig = $this->getUserDefaultConfig();

        $extend = [
            'avatar' => !empty($params['avatar']) ? $params['avatar'] : $userDefaultConfig['avatar'],
            'nickname' => !empty($params['nickname']) ? $params['nickname'] : $userDefaultConfig['nickname'] . $username,
            'group_id' => $userDefaultConfig['group_id'] ?? 1
        ];

        $ret = $this->auth->addUser($username, $password, $email, $mobile, $extend, $recUid);
        if ($ret) {
            $user = $this->auth->getUser();

            $user->verification = $verification;
            $user->save();

            $hookData = ['user' => $user];
            \think\Hook::listen('user_register_after', $hookData);

            return $this->auth;
        } else {
            error_stop($this->auth->getError());
        }
    }

    /**
     * 重置密码
     *
     * @param array $params 至少包含 mobile 和 email 中的一个
     * @return boolean
     */
    public function resetPassword($params)
    {
        $mobile = $params['mobile'] ?? null;
        $email = $params['email'] ?? null;
        $password = $params['password'] ?? null;

        if (!$params['mobile'] && !$params['email']) {
            error_stop('参数错误');
        }

        $user = UserModel::where(function ($query) use ($mobile, $email) {
            if ($mobile) {
                $query->whereOr('mobile', $mobile);
            }
            if ($email) {
                $query->whereOr('email', $email);
            }
        })->find();
        if (!$user) {
            error_stop(__('User not found'));
        }

        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($password, '', true);

        if(!$ret) {
            error_stop($this->auth->getError());
        }

        if ($ret) {
            $user = $this->auth->getUser();

            $verification = $user->verification;
            $verification->password = 1;
            $user->verification = $verification;
            $user->save();
        }

        return $ret;
    }

    /**
     * 修改密码
     *
     * @param string $old_password
     * @param string $password
     * @return boolean
     */
    public function changePassword($new_password, $old_password)
    {
        $ret = $this->auth->changepwd($new_password, $old_password);
        if(!$ret) {
            error_stop($this->auth->getError());
        }

        return $ret;
    }

    /**
     * 修改手机号
     * @param array $params
     * @return bool
     */
    public function changeMobile($params)
    {
        $user = auth_user();

        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $params['mobile'];
        $user->save();

        return true;
    }

    /**
     * 修改用户名
     * @param array $params
     * @return bool
     */
    public function changeUsername($params)
    {
        $user = auth_user();

        $verification = $user->verification;
        $verification->username = 1;
        $user->verification = $verification;
        $user->username = $params['username'];
        $user->save();

        return true;
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        $this->auth->logout();
    }

    /**
     * 注销用户
     */
    public function logoff()
    {
        $user = auth_user();
        $user = UserModel::get($user->id);

        $user->delete();

        $this->logout();
    }

    /**
     * 获取用户默认值配置
     *
     * @return object|array
     */
    private function getUserDefaultConfig()
    {
        $config = sheep_config('shop.user');
        return $config;
    }
}
